const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs').promises;
// 定义节点schema
const fileNodeSchema = new mongoose.Schema({
    name: { type: String, required: true },
    extname: { type: String, default: '' },
    path: { type: String, required: true },
    size: { type: Number, default: 0 },
    type: { type: String, required: true, enmu: ['file', 'directory', 'root'] },
    parent: { type: mongoose.Schema.Types.ObjectId, ref: 'FileTree', default: null },
    children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'FileTree', default: () => [] }],
    uploader: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    camera: { type: mongoose.Schema.Types.ObjectId, ref: 'Camera' },
}, { timestamps: true });

fileNodeSchema.pre('save', async function (next) {
    if (this.path && this.type === 'file') {
        try {
            const stats = await fs.stat(this.path);
            this.size = stats.size;
        } catch (error) {
            console.error(`Failed to get size of file ${this.path}`, error);
            next(error);
        }
    }
    next();
});

// 创建文件树模型
const FileNode = mongoose.model('File', fileNodeSchema, 'file');

module.exports = FileNode;
